package com.baidu.sggc.core.config;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@Configuration
@MapperScan(
        basePackages = {
                "com.baidu.sggc.mapper",
                "com.baidu.encrypt.mapper"
        },
        sqlSessionFactoryRef = "mysqlSqlSessionFactory"
)
public class MysqlDataSourceConfig {

  @Primary
  @Bean(name = "mysqlDataSource")
  @ConfigurationProperties(prefix = "spring.datasource") // 绑定配置文件中的配置
  public DataSource mysqlDataSource() {
    return DataSourceBuilder.create().build();
  }

  @Primary
  @Bean(name = "mysqlSqlSessionFactory")
  public SqlSessionFactory sqlSessionFactory(
      @Qualifier("mysqlDataSource") DataSource dataSource) throws Exception {
    MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
    bean.setDataSource(dataSource);

    // 开启数据源的小驼峰映射
    MybatisConfiguration configuration = new MybatisConfiguration();
    configuration.setMapUnderscoreToCamelCase(true);
    bean.setConfiguration(configuration);

    // 设置 Mapper XML 文件路径
    bean.setMapperLocations(
        new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
    return bean.getObject();
  }

  @Primary
  @Bean(name = "mysqlTransactionManager")
  public DataSourceTransactionManager transactionManager(
      @Qualifier("mysqlDataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }
}